﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Dexter.DataTransferObject;
using Dexter.Dependency;
using Dexter.Services;

namespace Dexter.Web.Mvc.Helpers {
	public static class MenuHelper {
		public static MvcHtmlString Menu ( this HtmlHelper helper, IEnumerable <PageStructureDto> pages ) {
			StringBuilder sb = new StringBuilder();

			IUrlBuilder u = DexterContainer.Resolve <IUrlBuilder> ( );

			sb.Append ( "<nav id=\"nav\"><ul>" );

			CreateElements ( sb,pages,u.Page);

			sb.Append ( "</ul></nav>" );

			return new MvcHtmlString ( sb.ToString() );
		}

		static void CreateElements ( StringBuilder sb, IEnumerable<PageStructureDto> pages, IPageUrlBuilder u ) {
			foreach (var page in pages) {
				sb.Append ( "<li>" );
				sb.Append ( MenuItem ( page, u ) );
				sb.Append ( "</li>" );
			}
		}

		static void CreateStructure ( StringBuilder sb, IEnumerable<PageStructureDto> pages, IPageUrlBuilder u ) {
			foreach ( var page in pages ) {
				CreateElements ( sb , pages , u );

				if (page.Pages != null && page.Pages.Any ( )) {
					sb.Append ( "<div class=\"drop\">" );
					sb.Append ( "<div class=\"drop-holder\">" );
					sb.Append ( "<div class=\"drop-frame\">" );
					sb.Append ( "<ul>" );

					CreateElements ( sb, page.Pages, u );

					sb.Append ( "</li>" );
					sb.Append ( "</ul>" );
					sb.Append ( "</div>" );
					sb.Append ( "</div>" );
					sb.Append ( "</div>" );
				}
					
			}
		}

		static string MenuItem ( PageStructureDto page, IPageUrlBuilder u ) {
			return string.Format ( "<a title=\"{0}\" href=\"{1}\">{0}</a>" , page.Title , u.Detail ( page ) );
		}
	}
}
